/*
 * Copyright (c) [2019] [Peking University]
 * [BDWare-DOIP] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 *
 *   http://license.coscl.org.cn/MulanPSL
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */
package bdware.netty.codec.doip;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

public class DoipUDPCodec extends MessageToMessageCodec<DatagramPacket, DOMessage> {
    public DoipUDPCodec() {}

    @Override
    protected void encode(ChannelHandlerContext ctx, DOMessage msg, List<Object> out)
            throws Exception {
        try {
            ByteBuf buff = Unpooled.buffer();
            encoder.encode(ctx, msg, buff);
            out.add(new DatagramPacket(buff, msg.getSender()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    MessageDecoder decoder = new MessageDecoder();
    MessageEncoder encoder = new MessageEncoder();

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out)
            throws Exception {
        decoder.decode(ctx, msg.content(), out);
        if (!out.isEmpty())
            for (Object obj : out) {
                if (obj != null && obj instanceof DOMessage) {
                    DOMessage doMsg = (DOMessage) obj;
                    doMsg.setSender(msg.sender());
                }
            }
    }
}
